# Definition for a Node.
class Node(object):
    def __init__(self, val=0, left=None, right=None, next=None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next


class Solution(object):
    def connect(self, root):
        """
        :type root: Node
        :rtype: Node
        """
        now_node = root
        while now_node:
            next_root = None
            next_node = None
            while True:
                print(now_node.val)
                if now_node.left:
                    if not next_root:
                        next_root = now_node.left
                        next_node = next_root
                    else:
                        next_node.next = now_node.left
                        next_node = next_root.next
                if now_node.right:
                    if not next_root:
                        next_root = now_node.right
                        next_node = next_root
                    else:
                        next_node.next = now_node.right
                        next_node = next_root.next
                if now_node.next:
                    now_node = now_node.next
                else:
                    break
            now_node = next_root
        return root